"use client";
import React, { useEffect } from "react";
import { useRouter } from "@/utils/router";
import { fetchApi } from "@/request/request";
import { showToast } from "@/components/ui/toast";
import { Mainbar } from "@/components/NavBar/mainBar";


interface allPost {
    _id: string;
    title: string;
    cover: string;
}


export default function Home() {
    const router = useRouter();
    const [allPost, setAllPost] = React.useState<allPost[]>([]);
    useEffect(() => {
        fetchApi("/api/home", { action: "init" })
            .then((res: any) => {
                setAllPost(res.data);
            })
            .catch((err) => {
                console.log(err);
                showToast("加载失败")
                setAllPost([]);
            });
    }, []); // 空数组确保只在组件加载时调用一次

    return (
        <>
            <div>
                <Mainbar />
            </div>
            <div className="flex flex-wrap items-center justify-center w-full mx-auto max-w-7xl gap-4 pt-25">
                {
                    allPost.map((item, index) => {
                        return (
                            <div key={index} className="mx-5 mb-5" onClick={() => { router.push(`/reader/${item._id}`) }}>
                                <div className="w-[7rem] h-[10rem] rounded-lg">
                                    <img className="w-full h-full object-cover rounded-lg" src={item.cover} alt={item.title} />
                                </div>
                                <span
                                    className="block text-ellipsis overflow-hidden whitespace-nowrap w-[7rem]"
                                    title={item.title}  // 添加 title 属性
                                >
                                    {item.title}
                                </span>
                            </div>
                        )
                    })
                }
            </div>
        </>
    )
}